package com.xjm.api.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjm.entity.vo.FileVo;
import com.xjm.entity.vo.PageVo;
import com.xjm.entity.vo.Result;
import com.xjm.enums.StatusEnum;
import com.xjm.entity.dto.FileDto;
import com.xjm.entity.model.FileModel;
import com.xjm.service.FileService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admin/file")
@RequiredArgsConstructor
public class FileController {

    private final FileService fileService;


    @GetMapping("/getFile")
    public Result<PageVo<FileModel>> getFile(Long page, Long size) {
        if (page == null || page < 1) {
            page = 1L;
        }

        if (size == null || size < 1) {
            size = 5L;
        }

        IPage<FileModel> paged = fileService.page(new Page<>(page, size));

        PageVo<FileModel> pageVo = new PageVo<>(page,size);
        pageVo.setTotal(paged.getTotal());
        pageVo.setList(paged.getRecords());
        pageVo.setCurrentPage(paged.getCurrent());
        pageVo.setPageSize(paged.getSize());

        return Result.success(pageVo);
    }

    /**
     * 分片上传文件
     * @param dto 文件信息
     * @return 上传结果
     */
    @PostMapping("/uploadChunk")
    public Result<FileVo> uploadChunk(@Validated FileDto dto) {
        FileVo fileVo = fileService.uploadChunk(dto);
        if (fileVo == null){
            return Result.error(StatusEnum.MERGE.code, "文件上传中");
        }
        return Result.success(fileVo);
    }

    /**
     * 检查文件是否已上传
     *
     * @param md5 文件MD5
     */
    @GetMapping("/checkFile/{md5}")
    public Result<FileVo> check(@PathVariable String md5) {
        return Result.success(fileService.checkFile(md5));
    }

    @GetMapping("/deleteFile/{id}")
    public Result<String> deleteFile(@PathVariable Long id) {
        fileService.delFile(id);
        return Result.success("删除成功");
    }
}
